using System;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using QQZiFramework;
using Microsoft.Extensions.Hosting;
using Microsoft.AspNetCore.Hosting;
using QQZiFramework.Mvc;
using Microsoft.AspNetCore.Http;
using System.Threading.Tasks;
using System.Net;
using Microsoft.AspNetCore.Diagnostics;

namespace QQZiCore.Mvc
{

    /// <summary>
    /// 未捕获异常处理类(FilterConfig.RegisterGlobalFilters中添加filters.Add(new QQZiFramework.Mvc.UnCatchErrorAttribute());)
    /// </summary>
    public class UnCatchErrorAttribute : ExceptionFilterAttribute
    { 
       
        public override void OnException(ExceptionContext filterContext)
        {
            Exception ex = filterContext.Exception;
            string msg;
            DBContext context = null;
            string oem = filterContext.RouteData.Values["OEM"] as string;
            if (oem == null)
            {
                context = new DBContext();
            }
            else
            {
                oem = oem.ToUpper();
                OEMMemberShip memberShip = OEMMemberShip.GetInstance(oem);
                context = memberShip.CreateDBContext();
            }

            using (context)
            {
                if (ex is NotLoginException)
                {
                    filterContext.Result = new ContentResult(){StatusCode =  StatusCodes.Status401Unauthorized ,Content = ex.Message };
                    filterContext.ExceptionHandled = true;
                    return;
                }
                if (ex is QQZiFramework.ClientException)
                {
                    msg = ex.Message;

                    context.LogMessage(msg);

                }
                else
                {
                    context.LogException(ex);

                    if (QQZiFramework.Mvc.Extension.Hosting.IsDevelopment())
                    {
                        msg = ex.Message;
                    }
                    else
                    {
                        msg = "服务器错误";

                        
                    }
                }
                context.Close();
                var path = filterContext.HttpContext.Request.Path.Value.ToLower();
               
                    filterContext.Result = new Controllers.WapResponse<string>(ex);
                    filterContext.ExceptionHandled = true;
                    return;
                
                
            }
        }
    }
}
